package com.godyao.mall.common.exception;

import com.godyao.mall.core.model.ResultCode;
import com.godyao.mall.core.model.ResultMsg;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.service.spi.ServiceException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author godyao
 * @date 2022/4/3
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {



    @ExceptionHandler(value = Exception.class)
    public ResultMsg<Void> handler(Exception ex) {
        ex.printStackTrace();

        if (ex instanceof BindException){
            log.error("参数错误：{}",ex.getMessage());
            List<FieldError> allErrors = ((BindException) ex).getFieldErrors();
            StringBuilder sb = new StringBuilder();
            for (FieldError errorMessage : allErrors) {
                sb.append(errorMessage.getField()).append(": ").append(errorMessage.getDefaultMessage()).append(", ");
            }
            return ResultMsg.resultFail(ResultCode.PARAMETER_FAIL.getCode(), sb.toString());
        }

        if (ex instanceof MethodArgumentNotValidException){
            log.error("参数错误：{}",ex.getMessage());
            return ResultMsg.<Void>resultFail(ResultCode.PARAMETER_FAIL.getCode(),ResultCode.PARAMETER_FAIL.getMsg());
        }

        if (ex instanceof ServerException){
            ServerException serviceException=(ServerException) ex;
            log.error("业务处理异常：{}",ex.getMessage());
            return ResultMsg.<Void>resultFail(serviceException.getCode(),serviceException.getMessage());
        }

        log.error("系统出现了异常：{}",ex.getMessage());
        return ResultMsg.<Void>resultFail();
    }
}
